<?php

declare(strict_types=1);

namespace Upside\Http;

class Response
{
    private string $content;
    private Status $status;

    /**
     * @var array<string, string>
     */
    private array $headers;
    private string $version = '1.0';

    /**
     * @param array<string, string> $headers
     */
    public function __construct(string $content = '', Status $status = Status::OK, array $headers = [])
    {
        $this->content = $content;
        $this->status = $status;
        $this->headers = $headers;
    }

    public function send(): static
    {
        $this
            ->send_headers()
            ->send_content();

        return $this;
    }

    private function send_headers(): static
    {
        if (\headers_sent()) {
            return $this;
        }

        foreach ($this->headers as $name => $value) {
            \header($name . ': ' . $value, true, $this->status->code());
        }

        \header(\sprintf('HTTP/%s %s %s', $this->version, $this->status->code(), $this->status->text()), true, $this->status->code());

        return $this;
    }

    private function send_content(): static
    {
        echo $this->content;

        return $this;
    }

    public function set_status(Status $status): static
    {
        $this->status = $status;

        return $this;
    }

    public function set_version(string $version): static
    {
        $this->version = $version;

        return $this;
    }
}
